import React, { Component } from 'react';
import { render } from 'react-dom';
import classnames from 'classnames';
import { Modal, Drawer, Button } from 'antd';

import CompDrag from '../Drag';

const { DragTitle } = CompDrag;
const defaultKey = 'basemodal';

// 弹框的key数据维护
const keyArr = [];

const divMap = {};

const getModalKey = (key) => {
  if (key) return key;
  return `${defaultKey}${Date.now()}`;
  // if (!key) return `${defaultKey}${Date.now()}`;
  // return keyArr.includes(key) ? `${key}${Date.now()}` : key;
};

const _create = (modalKey) => {
  if (!divMap[modalKey]) {
    const div = document.createElement('div');
    div.classList.add('base-modal');
    div.classList.add(`key-${modalKey}`);
    divMap[modalKey] = div;

    document.body.appendChild(div);
  }

  keyArr.push(modalKey);
  return divMap[modalKey];
};

const _open = (opts = {}) => {
  const { modalKey } = opts;
  const key = getModalKey(modalKey);

  _create(key);

  const element = <BaseModal {...opts} maskClosable={false} />;

  render(element, divMap[key]);
};

const _close = () => {
  // const { modalKey = lastKey } = opts;
  const modalKey = keyArr.pop();

  const element = <span />;
  render(element, divMap[modalKey]);
};


class BaseModal extends Component {
  static defaultProps = {
    title: '标题',
    content: null,
    onOk: undefined,
    onCancel: undefined,
    // 点击OK，自动关闭
    autoCloseOnOk: true,
    okText: '确定',
    cancelText: '取消',
    // 弹框类型： Modal: 弹框， Drawer: 抽屉
    type: 'Modal',
  };

  onCancel = () => {
    const { onCancel } = this.props;

    onCancel && onCancel();
    _close(this.props);
  };

  onOk = () => {
    const { onOk, autoCloseOnOk = true } = this.props;

    onOk && onOk();
    autoCloseOnOk && _close(this.props);
  };

  renderFoot() {
    const { type, footer } = this.props;
    if (type === 'Modal' || footer === null) return null;
    return (
      <div className="modal-foot">
        <Button onClick={this.onCancel} style={{ marginRight: 8 }}>
          取消
        </Button>
        <Button onClick={this.onOk} type="primary">
          确认
        </Button>
      </div>
    );
  }

  render() {
    const { className, content, onOk, onCancel, type, ...others } = this.props;

    const cls = classnames({
      'components-base-modal-render': true,
      [className]: !!className,
    });

    const Comp = type === 'Drawer' ? Drawer : Modal;

    return (
      <Comp {...others} title={<DragTitle title={others.title} />} visible className={cls} onClose={this.onCancel} onCancel={this.onCancel} onOk={this.onOk}>
        {content}
        {this.renderFoot()}
      </Comp>
    );
  }
}

BaseModal.open = _open;
BaseModal.close = _close;

export default BaseModal;
